﻿using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Microsoft.AspNet.Identity.EntityFramework;
using QuickPrompt.DomainModel;
using RedandBlue.EntityHelper;
using RedandBlue.RepositoryPattern.EF6;

namespace QuickPrompt.DataAccess
{
    public class QuickPromptContext : DataContext
    {
        static QuickPromptContext()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<QuickPromptContext>());
            Database.SetInitializer<QuickPromptContext>(null);
        }

        public QuickPromptContext()
            : base("Name=QuickPromptContext")
        {
        }

        public static QuickPromptContext Create()
        {
            return new QuickPromptContext();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder: modelBuilder); // This needs to go before the other rules!

           

            modelBuilder.Entity<QuickNote>().ToTable("QuickNote");

            RenameIdentityTables(modelBuilder);
           

            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            modelBuilder.Conventions.Add(new DateTime2Convention());
            modelBuilder.Properties<string>().Configure(c => c.HasColumnType("varchar"));

        }

        private static void RenameIdentityTables(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<IdentityUser>().ToTable("User").Property(p => p.Id).HasColumnName("UserGuid");
            //modelBuilder.Entity<IdentityUser<int, IdentityUserLogin<int>, IdentityUserRole<int>, IdentityUserClaim<int>>>().ToTable("Users");

            modelBuilder.Entity<IdentityRole>().ToTable("Role");
            //modelBuilder.Entity<IdentityRole<int, UserRole>>().ToTable("Roles");

            modelBuilder.Entity<IdentityUserRole>().ToTable("UserRole");
            //modelBuilder.Entity<IdentityUserRole<int>>().ToTable("UserRoles");

            modelBuilder.Entity<IdentityUserLogin>().ToTable("UserLogin");
            //modelBuilder.Entity<IdentityUserLogin<int>>().ToTable("UserLogins");

            modelBuilder.Entity<IdentityUserClaim>().ToTable("UserClaim");
            //modelBuilder.Entity<IdentityUserClaim<int>>().ToTable("UserClaims");
        }

        //public DbSet<UserBase> Users { get; set; }
        public DbSet<QuickNote> QuickNotes { get; set; }
        public DbSet<Prompt> Prompts { get; set; }
    }
}
